﻿using RockBus.Initialization.Interfaces;
using RockBus.Logging.Interfaces;
using RockBus.Routing.Interfaces;
using System;
using System.Reflection;

namespace RockBus.Routing
{
    public class PublisherManagerInitialization : IInitialization
    {
        public PublisherManagerInitialization(ILogger logger, IPublisherManager publisherManager)
        {
            this.Logger = logger;
            this.PublisherManager = publisherManager;
        }

        private ILogger Logger { get; set; }

        private IPublisherManager PublisherManager { get; set; }

        public void Initialize()
        {
            this.PublisherManager.EnableAll();
        }
    }

    public class PublisherManager : IPublisherManager
    {
        public PublisherManager(
            ILogger logger,
            IMessagePublisher[] messagePublishers)
        {
            this.Logger = logger;
            this.MessagePublishers = messagePublishers;
        }

        private ILogger Logger { get; set; }

        private IMessagePublisher[] MessagePublishers { get; set; }

        public void EnableAll()
        {
            if (null == this.MessagePublishers)
            {
                return;
            }

            foreach (IMessagePublisher mp in this.MessagePublishers)
            {
                try
                {
                    mp.Enable();
                }
                catch (Exception exc)
                {
                    Logger.Log(MethodBase.GetCurrentMethod(), exc);
                }
            }
        }

        public void DisableAll()
        {
            if (null == this.MessagePublishers)
            {
                return;
            }

            foreach (IMessagePublisher mp in this.MessagePublishers)
            {
                try
                {
                    mp.Disable();
                }
                catch (Exception exc)
                {
                    Logger.Log(MethodBase.GetCurrentMethod(), exc);
                }
            }
        }
    }
}